import exceptions.BussException;

import java.util.concurrent.*;

/**
 * Future的实现类为{@link FutureTask}, 直接看源码吧!
 *
 * Runnable也可以Future, 只不过返回的是null, 底层泛型是用了{@link Void}
 *
 * 自定义异常最终会被捕获并抛出ExecutionException
 */
public class FutureExecTest {

    public static void main(String[] args) {

        final ExecutorService exec = Executors.newFixedThreadPool(1);
        /* Runnable的future返回的都是null */
        Future future = exec.submit(() -> {
            try {
                Thread.sleep(200);
                throw new BussException("异常"); // 最终进入ExecutionException异常而不是BussException异常
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        try {
            Object ret = future.get(500, TimeUnit.MILLISECONDS); // 超时则直接抛TimeoutException
            System.out.println("任务成功返回:" + ret);
        } catch (TimeoutException e) {
            System.out.println("处理超时啦");
        } catch (InterruptedException e) {
            System.out.println("中断异常");
        } catch (ExecutionException e) {
            System.out.println("执行异常");
        } catch (BussException e) {
            System.out.println("Bus bus!!!");
        }
        exec.shutdown();
    }
}